import { defineStore } from "pinia";

export default defineStore("userStore", {
	state: () => {
		return {
			tokenName: '',
			token: '',
			refreshToken: '',
			userInfo: null,
			openId: '',
			unReadMsgNum: 0, 		// 未读消息数
		};
	},
	actions: {
		login(userInfo) {
			this.token = userInfo.token
			this.tokenName = userInfo.tokenName
			this.refreshToken = userInfo.refreshToken
			userInfo.user.roles = userInfo.roles
			this.userInfo = userInfo.user
		},
		getUser() {
			if(this.token && this.token !== ''){
				// 通过token向服务器获取用户信息，这里用到封装的apis请求接口
				return uni.$xl.apis.getUserInfo().then(res =>{
					// token登录成功
					this.userInfo = res.user
					return Promise.resolve("token获取user成功");
				}).catch(err =>{
					// token登录失败
					return Promise.reject(err);
				});
			}
			return Promise.reject("没有token");
		},
		logout() {
			this.token = ''
			this.tokenName = ''
			this.refresh_token = ''
			this.userInfo = null
			this.openId = ''
		},
		getUnReadMsgNum() {
			if(this.userInfo) {
				uni.$xl.apis.getUnReadNum().then(res => {;
					this.unReadMsgNum = res.data || 0
				})
			} else {
				this.unReadMsgNum = 0
			}
		},
	},
	unistorage: true, // 开启后对 state 的数据读写都将持久化
});